package com.hershel.userservice.config;

import com.hershel.userservice.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

//    @Autowired
//    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 也可用有参构造，取值范围是 4 到 31，默认值为 10。数值越大，加密计算越复杂
        return new BCryptPasswordEncoder(20);
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user").password(passwordEncoder().encode("password")).roles("USER");
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                //禁用CSRF保护
                .csrf().disable()
                //配置哪些URL需要认证，哪些不需要认证
                .authorizeRequests()
                //公开访问其路径
                .antMatchers("/login/**").permitAll()
                //其他所有请求都需要认证
                .anyRequest().authenticated()
                .and()
                //表单登录配置
                .formLogin()
                //自定义登录页面路径
                .loginPage("/login")
                //登录页面不需要认证即可访问
                .permitAll()
                .and()
                //登出配置
                .logout()
                //登出操作不需要认证即可访问
                .permitAll();
    }
}
